package com.fuzamei.rent.filter;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.google.gson.Gson;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

public class AccessFilter extends ZuulFilter {
    private Logger logger = LoggerFactory.getLogger(AccessFilter.class);
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        logger.info("发送 {} 请求到 {}",request.getMethod(),request.getRequestURI().toString());
        Object accessToken = request.getHeader("accessToken");
        //Object accessToken = request.getParameter("accessToken");
        if(accessToken == null){
            logger.warn("accessToken是空的");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(200);
            HttpServletResponse response = ctx.getResponse();
            try {
                response.setContentType("application/json;charset=UTF-8");
                OutputStream out = response.getOutputStream();
                Map<String,String> result = new HashMap<>();
                result.put("code","401");
                result.put("msg","用户鉴权失败，accessToken是空的");

                out.write(new Gson().toJson(result).getBytes("UTF-8"));

            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        logger.info("accessToken ok");
        return null;
    }
}
